# -*- coding: utf-8 -*-

#    OriginDB
#    Copyright (C) 2009  Jason Power <power.jg@gmail.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from PyQt4 import QtCore, QtGui
from ui_searchResults import Ui_SearchResultsFrame

class SearchResults(QtGui.QFrame):
	
	maxNameLength = 45
	
	def __init__(self, controller, mode=""):
		QtGui.QFrame.__init__(self)

		self.controller = controller

        # Set up the user interface from Designer.
		self.ui = Ui_SearchResultsFrame()
		self.ui.setupUi(self)

		self.objects = []
		self.reactions = []
		self.names = []

		self.setMode(mode)

		self.connect(self.ui.hidePushButton, QtCore.SIGNAL("clicked()"), self.close)
		self.connect(self.ui.addPushButton, QtCore.SIGNAL("clicked()"), self.addItem)
		self.connect(self.ui.searchResultListWidget, QtCore.SIGNAL("itemDoubleClicked (QListWidgetItem *)"), self.doubleClick)
		self.connect(self.ui.viewReactionPushButton, QtCore.SIGNAL("clicked()"), self.viewReaction)
		self.connect(self.ui.viewCompoundPushButton, QtCore.SIGNAL("clicked()"), self.updateItemShown)
		self.connect(self.ui.clearPushButton, QtCore.SIGNAL("clicked()"), self.clear)
		self.connect(self.ui.viewReferencePushButton, QtCore.SIGNAL("clicked()"), self.updateItemShown)

	def addCompounds(self, compounds):
		for i in compounds:
			self.objects.append(i)
			name = i.name
			if len(name) > self.maxNameLength:
				name = name[0:self.maxNameLength]+'...'
			self.names.append(name)

		for i in self.names[self.ui.searchResultListWidget.count():]:
			self.ui.searchResultListWidget.addItem(i)
			
		self.ui.searchResultListWidget.setCurrentRow(0)

	def addReferences(self, references):
		for i in references:
			self.objects.append(i)
			author = i.author_name[0:i.author_name.find(';')]
			year = i.year
			if year == 1800:
				year = ""
			else:
				year = str(year)
			name = "(%s %s) %s" % (author, year, i.title)
			if len(name) > self.maxNameLength:
				name = name[0:self.maxNameLength]+'...'
			self.names.append(name)

		for i in self.names[self.ui.searchResultListWidget.count():]:
			self.ui.searchResultListWidget.addItem(i)
			
		self.ui.searchResultListWidget.setCurrentRow(0)

	def addCatalysts(self, catalysts):
		for i in catalysts:
			self.objects.append(i)
			name = i.name
			if len(name) > self.maxNameLength:
				name = name[0:self.maxNameLength]+'...'
			self.names.append(name)

		for i in self.names[self.ui.searchResultListWidget.count():]:
			self.ui.searchResultListWidget.addItem(i)
			
		self.ui.searchResultListWidget.setCurrentRow(0)

	def addReactions(self, reactions):
		""" Reactions is a dict of {reaction:[compounds]}
		"""
		
		for react in reactions:
			print react.key
			if react.reference and react.reference.key:
				reactAuthor = react.reference.author_name[0:react.reference.author_name.find(';')]
				reactYear = str(react.reference.year)
			else:
				reactAuthor = "Unknown"
				reactYear = ""
			for comp in reactions[react]:
				self.objects.append(comp)
				name = comp.name+" (%s %s)" % (reactAuthor, reactYear)
				if len(name) > self.maxNameLength:
					name = name[0:self.maxNameLength]+'...' 
				self.names.append(name)
				self.reactions.append(react)

		for i in self.names[self.ui.searchResultListWidget.count():]:
			self.ui.searchResultListWidget.addItem(i)
			
		self.ui.searchResultListWidget.setCurrentRow(0)

	def setMode(self, mode):
		self.mode = mode
		if self.mode == "Compound":
			self.ui.searchInfoLabel.setText("Compound Search")
			self.ui.addReactantRadioButton.hide()
			self.ui.addProductRadioButton.hide()
			self.ui.addCatalystRadioButton.hide()
			self.ui.addPushButton.hide()
			self.ui.viewReferencePushButton.hide()
			self.ui.viewCompoundPushButton.show()
			self.ui.viewReactionPushButton.show()
			self.ui.viewReactionPushButton.setEnabled(False)
		elif self.mode.find("Products")!=-1 or self.mode.find("Reactants") !=-1:
			self.ui.searchInfoLabel.setText(self.mode)
			self.ui.addReactantRadioButton.hide()
			self.ui.addProductRadioButton.hide()
			self.ui.addCatalystRadioButton.hide()
			self.ui.viewCompoundPushButton.show()
			self.ui.addPushButton.hide()
			self.ui.viewReferencePushButton.hide()
			self.ui.viewReactionPushButton.show()
			self.ui.viewReactionPushButton.setEnabled(True)
		elif self.mode == "Reference":
			self.ui.searchInfoLabel.setText("Reference Search")
			self.ui.addReactantRadioButton.hide()
			self.ui.addProductRadioButton.hide()
			self.ui.addCatalystRadioButton.hide()
			self.ui.viewCompoundPushButton.hide()
			self.ui.viewReferencePushButton.show()
			self.ui.addPushButton.hide()
			self.ui.viewReactionPushButton.hide()
		elif self.mode == "Adding Reactant":
			self.ui.searchInfoLabel.setText("Adding")
			self.ui.addReactantRadioButton.show()
			self.ui.addProductRadioButton.show()
			self.ui.addCatalystRadioButton.hide()
			self.ui.viewReferencePushButton.hide()
			self.ui.viewCompoundPushButton.hide()
			self.ui.addPushButton.show()
			self.ui.addReactantRadioButton.setChecked(True)
			self.ui.viewReactionPushButton.hide()
		elif self.mode == "Adding Product":
			self.ui.searchInfoLabel.setText("Adding")
			self.ui.addReactantRadioButton.show()
			self.ui.addProductRadioButton.show()
			self.ui.viewReferencePushButton.hide()
			self.ui.viewCompoundPushButton.hide()
			self.ui.addCatalystRadioButton.hide()
			self.ui.addPushButton.show()
			self.ui.addProductRadioButton.setChecked(True)
			self.ui.viewReactionPushButton.hide()
		elif self.mode == "Adding Catalyst":
			self.ui.searchInfoLabel.setText("Adding")
			self.ui.addReactantRadioButton.hide()
			self.ui.addProductRadioButton.hide()
			self.ui.addCatalystRadioButton.show()
			self.ui.viewCompoundPushButton.hide()
			self.ui.viewReferencePushButton.hide()
			self.ui.addPushButton.show()
			self.ui.addCatalystRadioButton.setChecked(True)
			self.ui.viewReactionPushButton.hide()
		elif self.mode == "Adding Reference":
			self.ui.searchInfoLabel.setText("Adding")
			self.ui.addReactantRadioButton.hide()
			self.ui.addProductRadioButton.hide()
			self.ui.viewCompoundPushButton.hide()
			self.ui.addCatalystRadioButton.hide()
			self.ui.viewReferencePushButton.hide()
			self.ui.addPushButton.show()
			self.ui.viewReactionPushButton.hide()
		else:
			if mode:
				self.ui.searchInfoLabel.setText(mode)
			else:
				self.ui.searchInfoLabel.setText("(blank search)")
			self.ui.addReactantRadioButton.hide()
			self.ui.addProductRadioButton.hide()
			self.ui.addCatalystRadioButton.hide()
			self.ui.addPushButton.hide()
			self.ui.viewReactionPushButton.hide()
			self.ui.viewReferencePushButton.hide()
			self.ui.viewCompoundPushButton.hide()

	def clear(self):
		self.mode = ""
		self.ui.searchResultListWidget.clear()
		self.objects = []
		self.names = []
		self.relations = []
		self.ui.searchInfoLabel.setText("(blank search)")

	def updateItemShown(self, item=None):
		if not self.mode or self.mode.find("Adding") != -1:
			return

		obj = self.objects[self.ui.searchResultListWidget.currentRow()]

		if self.mode == "Compound" or self.mode.find("Reactants")!=-1 or self.mode.find("Products")!=-1:
			self.controller.setViewCurrentCompound(obj)
		elif self.mode == "Reference":
			self.controller.setViewCurrentReference(obj)

	def getSelected(self):
		return self.objects[self.ui.searchResultListWidget.currentRow()]

	def doubleClick(self, item):
		if not self.mode:
			return

		elif self.mode.find("Adding") != -1:
			self.addItem(item)

		else:
			self.updateItemShown(item)

	def addItem(self, item=None):
		if self.mode.find("Adding") != -1:
			if self.ui.searchResultListWidget.currentRow() != -1:
				if self.mode == "Adding Reference":
					self.controller.addToReaction(self.objects[self.ui.searchResultListWidget.currentRow()], "Reference")
				elif self.ui.addProductRadioButton.isChecked():
					self.controller.addToReaction(self.objects[self.ui.searchResultListWidget.currentRow()], "Product")
				elif self.ui.addReactantRadioButton.isChecked():
					self.controller.addToReaction(self.objects[self.ui.searchResultListWidget.currentRow()], "Reactant")
				elif self.ui.addCatalystRadioButton.isChecked():
					self.controller.addToReaction(self.objects[self.ui.searchResultListWidget.currentRow()], "Catalyst")

	def viewReaction(self):
		self.controller.setViewCurrentReaction(self.reactions[self.ui.searchResultListWidget.currentRow()])